package main

import (
	"log"
	"net/http"
	"os"
	"path/filepath"
	"websocket/internal/handler"
)

func main() {
	// 获取到当前工作目录
	currentDir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	staticDir := filepath.Join(currentDir, "static")

	// 设置静态文件路由
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir(staticDir))))

	websocketHandler := handler.NewWebsocketHandler()

	// websocket 路由
	http.HandleFunc("/ws", websocketHandler.HandlerConnections)

	// 根路径重定向 index.html
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" {
			http.Redirect(w, r, "/static/index.html", http.StatusFound)
			return
		}
		http.NotFound(w, r)
	})

	log.Println("服务器启动在: localhost:9091")

	// 启动服务器
	err = http.ListenAndServe(":9091", nil)
	if err != nil {
		log.Fatal("服务器启动失败: ", err)
	}

}
